package com.chidopi.market.aa.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.chidopi.cdf.dao.IBaseDao;
import com.chidopi.cdf.exception.CdfException;
import com.chidopi.cdf.service.IBaseService;
import com.chidopi.market.aa.domain.Accounts;
import com.chidopi.market.aa.domain.FunctionItems;
import com.chidopi.market.aa.domain.Functions;
import com.chidopi.market.aa.domain.Roles;

public class RoleServiceImpl implements IBaseService<Roles> {
	private static Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);
	@Autowired
	@Qualifier("roleDao")
	private IBaseDao<Roles> baseDao;

	@Autowired
	@Qualifier("accountDao")
	private IBaseDao<Accounts> accountDao;

	@Autowired
	@Qualifier("functionDao")
	private IBaseDao<Functions> functionDao;

	@Autowired
	@Qualifier("itemDao")
	private IBaseDao<FunctionItems> itemDao;

	public int delete(Roles t) throws Exception {
		Integer id = t.getId();
		List<Accounts> accounts = this.accountDao.find("id in (select account_id from account2role where role_id=?) ", id);
		if (accounts.size() > 0) {
			logger.debug("delete [" + id + "] failure: account2role.size()=" + accounts.size());
			throw new CdfException("error.role.delete.account2role");
		}
		List<Functions> functions = this.functionDao.find("id in (select function_id from role2function where role_id=?) ", id);
		if (functions.size() > 0) {
			logger.debug("delete [" + id + "] failure: role2function.size()=" + accounts.size());
			throw new CdfException("error.role.delete.role2function");
		}
		return this.baseDao.delete(t);
	}

	public List<Roles> find(String sqlWhere, Object... args) throws Exception {
		logger.debug(sqlWhere);
		return this.baseDao.find(sqlWhere, args);
	}

	public Roles findById(Object id) throws Exception {
		logger.debug("id=" + id);
		Roles role = this.baseDao.findById(id);
		if (null != role) {
			List<Accounts> accounts = this.accountDao.find("id in (select account_id from account2role where role_id=?) ", id);
			role.setAccounts(accounts);
			List<Functions> functions = this.functionDao.find("id in (select function_id from role2function where role_id=?) ", id);
			role.setFunctions(functions);
			List<FunctionItems> items = this.itemDao.find("id in (select item_id from role2functionitem where role_id=?) ", id);
			role.setFunctionItems(items);
		}
		return role;
	}

	public int insert(Roles t) throws Exception {
		return this.baseDao.insert(t);
	}

	public int update(Roles t) throws Exception {
		return this.baseDao.update(t);
	}

	public int getNextSequence() throws Exception {
		return this.baseDao.getSeqNextValue();
	}
}
